import { IndicatorLayer } from '../index';
import MultiLine from '../../../base/MultiLine';
import Point from '../../../core/Point';

export default class extends IndicatorLayer {
    caculate() {
        const { dataStart, dataEnd, data = [], params } = this;
        const { N = 5 } = params;
        console.log('N====>', N, params);
        const maN = [];
        for (let i = dataStart; i <= dataEnd; i++) {
            let ma = 0;
            for (let j = 0; j < N; j++) {
                ma += data[i - j] ? data[i - j].close : 0;
            }
            ma /= N;
            maN.push(ma);
            if (this.max < ma) {
                this.max = ma;
            }
            if (this.min > ma) {
                this.min = ma;
            }
        }
        this.resultMa = maN;
    }

    render(option) {
        this.childs.splice(0);
        const { resultMa = [] } = this;
        const { min, xStep, yStep } = option;
        const points = [];
        for (let i = 0; i < resultMa.length; i++) {
            const y = Math.round((resultMa[i] - min) * yStep);
            if (i === 0) {
                points.push(new Point(
                    Math.round(i * xStep),
                    y,
                ));
            }
            const x = Math.round((i + 0.5) * xStep);
            points.push(new Point(x, y));
        }
        const line = new MultiLine(this.canvas, {
            color: this.color,
            lineWidth: this.lineWidth,
            left: 0,
            bottom: 0,
        }, points);
        this.addChild(line);
    }

    getIndicator(pos) {
        const { resultMa = [], params = {} } = this;
        const { N = 5 } = params;
        return {
            name: `${this.name}${N}`,
            value: resultMa[pos] ? resultMa[pos] : '--'
        };
    }
}
